<?php
class agentModel extends RPHP_Model
{

    protected $_auth = null;

    //检查权限
    public function checkPriv($pv, $return = true, $menu = true)
    {
        $this->_auth = $this->auth->CheckPriv($pv, $return, $menu);
        return $this->_auth;
    }

/*商品*/
    //获取单个商品
    public function getSingleGoods($goods_id)
    {

        $sql = "SELECT * FROM {$this->_prefix['primary']}agent_goods WHERE `goods_id`=" . intval($goods_id) . " AND `status`<3 LIMIT 1";
        return $this->db->getrow($sql);
    }

    //商品列表
    public function getGoods($stat = "", $para, $page = 1, $pagesize = 10)
    {

        $where = "  `status`<3";

        if ($para['keyword'] != '') {
            $where .= " AND (`name` LIKE '%" . $para['keyword'] . "%')";
        }

        $sql = "SELECT COUNT(`goods_id`) AS `cnt` FROM {$this->_prefix['primary']}agent_goods WHERE " . $where;

        $cnt = $this->db->getone($sql);
        if ($cnt > 0) {
            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "`goods_id` DESC";

            $rssql = "SELECT * FROM {$this->_prefix['primary']}agent_goods WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;
            $rs    = $this->sql($rssql);

        }

        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt / $pagesize),
            'count'   => $cnt,
            'data'    => $rs,
            'para'    => $para,
        );
    }

    //保存商品
    public function saveGoods($da, $goods_id = 0)
    {
        $code          = 900;
        $field['name'] = addslashes(htmlspecialchars(trim($da['goods_name'])));

        $field['market_price'] = number_format($da['market_price'], 2, '.', '');

        $field['price_2'] = number_format($da['price_2'], 2, '.', '');
        $field['price_3'] = number_format($da['price_3'], 2, '.', '');
        $field['price_4'] = number_format($da['price_4'], 2, '.', '');

        $field['recommend_2'] = number_format($da['recommend_2'], 2, '.', '');
        $field['recommend_3'] = number_format($da['recommend_3'], 2, '.', '');
        $field['recommend_4'] = number_format($da['recommend_4'], 2, '.', '');

        //保存商品
        if ($field['name'] != "") {
            $code = 403;
            //开始事务
            $this->db->begin();
            $rollback = true;

            //修改
            if ($goods_id > 0) {
                $goods = $this->getSingleGoods($goods_id);
                if ($goods) {

                    //其他必须字段
                    $field['last_edit'] = $_SERVER['REQUEST_TIME'];
                    $field['last_aid']  = $this->_auth['aid'];
                    $field['status']    = intval($da['stat']);

                    //修改商品
                    $sql = "UPDATE {$this->_prefix['primary']}agent_goods SET ";
                    foreach ($field as $key => $value) {
                        $upsql[] = "`" . $key . "`='" . $value . "'";
                    }
                    $sql .= implode(",", $upsql) . " WHERE `goods_id`=" . $goods['goods_id'];

                    $rcnum = $this->sql($sql);
                    if ($rcnum > 0) {

                        $code = 200;
                        $this->db->commit();
                        $rollback = false;
                    }

                } else {
                    $code = 404;
                }

            }
            //新增
            else {

                //其他必须字段
                $field['create_time'] = $field['last_edit'] = $_SERVER['REQUEST_TIME'];
                $field['last_aid']    = $this->_auth['aid'];

                foreach ($field as $key => $value) {
                    $keys[]   = "`" . $key . "`";
                    $values[] = "'" . $value . "'";
                }

                //插入商品
                $sql = "INSERT INTO {$this->_prefix['primary']}agent_goods (" . implode(",", $keys) . ") VALUES (" . implode(",", $values) . ")";

                $goods_id = $this->sql($sql);
                if ($goods_id > 0) {

                    $code = 200;
                    $this->db->commit();
                    $rollback = false;

                }

            } //end of add

            if ($rollback) {
                $this->db->rollback();
            }

        }

        return $code;
    }

/*设置*/

    public function getAllGoods()
    {
        $sql = "SELECT `goods_id`,`name` FROM {$this->_prefix['primary']}agent_goods ORDER BY `goods_id` ASC";
        $tmp = $this->sql($sql);
        if ($tmp) {
            foreach ($tmp as $r) {
                $goods[$r['goods_id']] = stripslashes($r['name']);
            }

            return $goods;
        }

    }

    // 获取设置
    public function getSetting()
    {
        $sql  = "SELECT `id`,`content`,`status`,`agent_level` FROM {$this->_prefix['primary']}agent_setting WHERE `status`<3 ORDER BY `agent_level` ASC";
        $data = $this->sql($sql);

        if ($data) {

            foreach ($data as $r) {
                $new[$r['agent_level']][] = $r;
            }

            return array(
                'data'  => $new,
                'goods' => $this->getAllGoods(),
            );
        }
    }

    //保存设置
    public function saveSetting($da, $id = 0)
    {
        $code = 900;

        $field['agent_level'] = intval($da['agent_level']);
        $field['content']     = json_encode($da['goods']);

        //保存商品
        if ($field['agent_level'] > 1 && $field['agent_level'] < 5) {
            $code = 403;
            //开始事务
            $this->db->begin();
            $rollback = true;

            //修改
            if ($id > 0) {
                $goods = $this->getSingleSetting($id);
                if ($goods) {

                    //其他必须字段
                    $field['last_edit'] = $_SERVER['REQUEST_TIME'];
                    $field['last_aid']  = $this->_auth['aid'];
                    $field['status']    = intval($da['stat']);

                    //修改商品
                    $sql = "UPDATE {$this->_prefix['primary']}agent_setting SET ";
                    foreach ($field as $key => $value) {
                        $upsql[] = "`" . $key . "`='" . $value . "'";
                    }
                    $sql .= implode(",", $upsql) . " WHERE `id`=" . $goods['id'];

                    $rcnum = $this->sql($sql);
                    if ($rcnum > 0) {

                        $code = 200;
                        $this->db->commit();
                        $rollback = false;
                    }

                } else {
                    $code = 404;
                }

            }
            //新增
            else {

                //其他必须字段
                $field['create_time'] = $field['last_edit'] = $_SERVER['REQUEST_TIME'];
                $field['last_aid']    = $this->_auth['aid'];

                foreach ($field as $key => $value) {
                    $keys[]   = "`" . $key . "`";
                    $values[] = "'" . $value . "'";
                }

                //插入商品
                $sql = "INSERT INTO {$this->_prefix['primary']}agent_setting (" . implode(",", $keys) . ") VALUES (" . implode(",", $values) . ")";

                $id = $this->sql($sql);
                if ($id > 0) {

                    $code = 200;
                    $this->db->commit();
                    $rollback = false;

                }

            } //end of add

            if ($rollback) {
                $this->db->rollback();
            }

        }

        return $code;
    }

    //获取单个设置
    public function getSingleSetting($id)
    {

        $sql = "SELECT * FROM {$this->_prefix['primary']}agent_setting WHERE `id`=" . intval($id) . " AND `status`<3 LIMIT 1";
        return $this->db->getrow($sql);
    }

/*库存*/

    public function getUser($uid)
    {
        $sql = "SELECT `uid`,`name`,`mobile` FROM {$this->_prefix['primary']}member_account WHERE `uid`=" . $uid;
        return $this->db->getrow($sql);
    }

    public function getStock($uid)
    {
        $sql = "SELECT `goods_id`,`number` FROM {$this->_prefix['primary']}agent_stock WHERE `uid`=" . $uid;
        $tmp = $this->sql($sql);
        if ($tmp) {

            foreach ($tmp as $r) {
                $data[$r['goods_id']] = $r['number'];
            }

            return $data;
        }
    }

    public function saveRecharge($da)
    {

        $code = 900;

        $uid      = intval($da['uid']);
        $goods_id = intval($da['goods_id']);
        $number   = intval($da['number']);

        if ($uid > 0 && $goods_id > 0 && $number != 0) {

            $this->db->begin();
            $commit = false;
            $code   = 403;

            // 增加库存
            $sql = "SELECT `id` FROM {$this->_prefix['primary']}agent_stock WHERE `uid`=" . $uid . " AND `goods_id`=" . $goods_id;
            $id  = $this->db->getone($sql);

            if ($id > 0) {
                $sql = "UPDATE {$this->_prefix['primary']}agent_stock SET `number`=`number`+" . $number . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . " WHERE `id`=" . $id;
            } else {
                $sql = "INSERT INTO {$this->_prefix['primary']}agent_stock (`uid`,`goods_id`,`number`,`update_time`) VALUES (" . $uid . "," . $goods_id . "," . $number . "," . $_SERVER['REQUEST_TIME'] . ")";
            }

            $rcb = $this->sql($sql);
            if ($rcb > 0) {
                // 插入记录
                $sql = "INSERT INTO {$this->_prefix['primary']}agent_stock_log (`goods_id`,`to_uid`,`aid`,`number`,`create_time`,`separate_type`) VALUES (" . $goods_id . "," . $uid . "," . $this->_auth['aid'] . "," . $number . "," . $_SERVER['REQUEST_TIME'] . ",2)";

                $rca = $this->sql($sql);
                if ($rca > 0) {
                    $code   = 200;
                    $commit = true;
                }
            }

            if ($commit) {
                $this->db->commit();
            } else {
                $this->db->rollback();
            }

        }

        return array(
            'code' => $code,
        );
    }
}
